'use strict';
const { Controller } = require('egg');
const COS = require('cos-nodejs-sdk-v5');
const CosConfig = {
  SecretId:'AKID2zqDdSJG7rUzSjuxpYAh1CAztZ6RdfYE',
  SecretKey:'d9VfcNxJRn391f4f7NSK4gAYkkaCbnmY',
  Bucket: 'diandian-1300713889',
  Region: 'ap-shanghai',
  Uin: '',
};
const cos = new COS({
  SecretId: CosConfig.SecretId, // 推荐使用环境变量获取；用户的 SecretId，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参考https://cloud.tencent.com/document/product/598/37140
  SecretKey: CosConfig.SecretKey, // 推荐使用环境变量获取；用户的 SecretKey，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参考https://cloud.tencent.com/document/product/598/37140
});
class UploadController extends Controller {
  /**
   * 腾讯oss上传
   */
  async file() {
    const file = await this.ctx.getFileStream(); // 获取上传的文件
    if (file.filename.length > 64) {
      throw new Error('文件名不能超过64个字符');
    }
    try {
      const result = await cos.putObject({
        Bucket: CosConfig.Bucket, // Bucket 格式：test-1250000000
        Region: CosConfig.Region, // 例如 ap-beijing
        Key: file.filename, // 文件名
        Body: file, // 文件路径
      });
      console.log('result',result)
      this.ctx.success({
        name: file.filename,
        url:'https://' + result.Location
      });
    } catch (e) {
      console.log(e)
    }
  }

}

module.exports = UploadController;
